<?php

namespace app\common\model;

use think\Model;


class Change extends Model
{

    

    

    // 表名
    protected $name = 'change';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [

    ];
    

    







    public function user()
    {
        return $this->belongsTo('User', 'user_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }


    public function enterprise()
    {
        return $this->belongsTo('Enterprise', 'enterprise_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    /**
     * 列表
     */
    public static function getList($data=[])
    {
        $where = '1=1';
        $order = 'a.id desc';
        $page  = isset($data['page']) && !empty($data['page']) ? intval($data['page']) : 1;
        $limit  = isset($data['limit']) && !empty($data['limit']) ? intval($data['limit']) : 10;
        $start = ($page-1)*$limit;

        $field = "a.*, c.mobile";

        $list = db('change')
            ->alias('a')
            ->join('enterprise b', 'a.enterprise_id = b.id')
            ->join('user c', 'a.user_id = c.id')
            ->where($where)
            ->order($order)
            ->limit($start, $limit)
            ->field($field)
            ->select();
        if(!empty($list))
        {
            foreach ($list as &$v)
            {
                $v['createtimeText'] = isset($v['createtime']) && !empty($v['createtime']) ? date('Y-m-d H:i:s', $v['createtime']) : '';
                $v['changeCategoryArr'] = json_decode($v['change_category'], true);
                foreach ($v['changeCategoryArr'] as &$v1)
                {
                    $v1['change_category_name'] = db('change_category')
                        ->where("id={$v1['id']}")
                        ->value('name');
                    /*if($v1['change_category_name']=='经营场所')
                    {
                        $v1['old_addresses'] = $v['addresses'];
                        $v1['old_area'] = '';
                    }*/
                }
                unset($v1);

                // 公司信息
                $v['enterpriseInfo'] = Enterprise::getInfo("id={$v['enterprise_id']}");

                // 相对路径
                $v['sortFile'] = $v['templateFile'] ? str_replace(request()->domain(), '', $v['templateFile']) : '';
            }
            unset($v);
        }

        $total = db('change')
            ->alias('a')
            ->join('enterprise b', 'a.enterprise_id = b.id')
            ->join('user c', 'a.user_id = c.id')
            ->where($where)
            ->count();

        return [
            'list' => $list,
            'total' => $total,
        ];

    }

}
